<template>
  <!--标签管理-->
  <div style="padding:10px;">
    <el-card class="box-card">
      <div v-if="subjectName" slot="header" class="clearfix">
        <el-breadcrumb separator-class="el-icon-arrow-right">
          <el-breadcrumb-item>学科管理</el-breadcrumb-item>
          <el-breadcrumb-item>{{subjectName}}</el-breadcrumb-item>
          <el-breadcrumb-item>标签管理</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- 搜索区域 -->
      <el-row>
        <el-col :span="20">
          <el-form size="mini" ref="form" :inline="true" :model="form" label-width="80px">
            <el-form-item label="标签名称">
              <el-input v-model="form.tagName"></el-input>
            </el-form-item>
            <el-form-item label="状态">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option label="启用" value="1"></el-option>
                <el-option label="禁用" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button @click="clear">清除</el-button>
              <el-button type="primary" @click="loadTags(1)">查询</el-button>
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="4">
          <el-button v-if="subjectName" type="text" @click="goBack">← 返回学科</el-button>
          <el-button size="mini" type="success" icon="el-icon-edit" @click="show('add')">新增标签</el-button>
        </el-col>
      </el-row>
      <!-- 统计条 -->
      <el-alert :title="cTitle" type="info" :closable="false" show-icon>
      </el-alert>
      <!-- 表格 -->
      <el-table :data="tableData" border style="width: 100%" class="mt10" v-loading="isLoading">
        <el-table-column type="index" width="50">
        </el-table-column>
        <el-table-column prop="subjectName" label="所属学科">
        </el-table-column>
        <el-table-column prop="tagName" label="标签名称">
        </el-table-column>
        <el-table-column prop="username" label="创建者">
        </el-table-column>
        <el-table-column prop="addDate" label="创建日期">
          <template v-slot="{row}">
        {{row.addDate|parseTimeByString}}
          </template>
        </el-table-column>
        <el-table-column prop="state" label="状态">
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click="clickChangeState(scope.row.id,scope.row.state)" type="text" size="small">
              {{ scope.row.state === '启用' ? '禁用' : '启用' }}
            </el-button>
            <el-button :disabled="scope.row.state === '启用'" type="text" size="small" @click="show('modify',scope.row)">修改</el-button>
            <el-button :disabled="scope.row.state === '启用'" type="text" size="small" @click="remove(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div style="text-align:right;">
        <el-pagination background layout="prev, pager, next,sizes, jumper" class="mt10" @size-change="handleSizeChange" @current-change="handleCurrentChange" :page-sizes="[5, 10, 20, 50]" :total="tagCounts" :page-size="pageSize" :current-page="currentPage">
        </el-pagination>
      </div>
    </el-card>
    <!-- 新增&修改模态框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="350px">
      <el-form :model="form" :rules="rules" ref="ruleForm">
        <el-form-item v-if="!subjectID" label="所属学科" :label-width="formLabelWidth" size="mini" prop="subject">
          <el-select v-model="form.subject" placeholder="请选择" style="width:100%;">
            <el-option v-for="item in subjectsLists" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="标签名称" :label-width="formLabelWidth" size="mini" prop="dirname">
          <el-input v-model="form.dirname" placeholder="请输入标签名称"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align:right;">
        <el-button @click="dialogFormVisible = false" size="mini">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="mini">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 删除提示弹层 -->
  </div>
</template>

<script>
import { list as getTags, changeState, remove, add, update } from '@/api/hmmm/tags.js'
import { simple as subJectsList } from '@/api/hmmm/subjects.js'
import { parseTimeByString } from '@/filters'
export default {
  filters: {
    parseTimeByString
  },
  data () {
    return {
      input: '',
      form: {
        tagName: '',
        state: '',
        subject: '',
        dirname: ''
      },
      rules: {
        subject: [
          { required: true, message: '请选择所属学科', trigger: 'change' }
        ],
        dirname: [
          { required: true, message: '请输入标签名称', trigger: 'blur' }
        ]
      },
      tableData: [],
      currentPage4: 4,
      dialogFormVisible: false,
      formLabelWidth: '80px',
      // 表格加载
      isLoading: false,
      // 分页
      tagCounts: 0,
      // 显示条数:默认10
      pageSize: 10,
      // 当前页数,默认第1页
      currentPage: 1,
      // 模态框标题
      dialogTitle: '新增标签',
      subjectsLists: [],
      currentModifyId: '',
      // 路由传参过来的id和name
      subjectID: '',
      subjectName: ''
    }
  },
  computed: {
    cTitle () {
      return '数据一共 ' + this.tagCounts + '条'
    }
  },
  methods: {
    // 提交新增标签弹窗
    submitForm () {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 通过校验
          if (this.dialogTitle === '修改标签') {
            this.updateTags(this.currentModifyId)
          } else {
            this.addTags()
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 分页
    handleSizeChange (pagesize) {
      console.log(`每页 ${pagesize} 条`)
      this.pageSize = pagesize
      this.loadTags(1)
    },
    handleCurrentChange (page) {
      console.log(`当前第 ${page} 页`)
      this.loadTags(page)
    },
    // 控制新增和修改模态框的显示
    show (type, rowData) {
      this.dialogFormVisible = true
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.resetFields()
      }
      this.dialogTitle = type === 'add' ? '新增标签' : '修改标签'
      // 若果是修改 我是不是要获取当前行数据 回显到模态框
      if (rowData) {
        this.form.dirname = rowData.tagName
        this.form.subject = rowData.subjectID
        this.currentModifyId = rowData.id
      } else {
        this.form.dirname = ''
        this.form.subject = ''
        this.currentModifyId = ''
      }
    },
    // 控制删除提示弹层
    remove (id) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.removeTags(id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 清除
    clear () {
      this.form.tagName = ''
      this.form.state = ''
    },
    // 获取数据列表
    async loadTags (page) {
      this.isLoading = true
      // 请求参数
      // 请求接口 携带参数
      const params = {
        page,
        pagesize: this.pageSize
      }
      // 如果标签名称不为空
      if (this.form.tagName) {
        params.tagName = this.form.tagName
      }
      // 如果筛选了状态
      if (this.form.state) {
        params.state = this.form.state
      }
      // 如果有路由传参
      if (this.subjectID) {
        params.subjectID = this.subjectID
      }
      var { data: res } = await getTags(params)
      // 渲染表格数据
      res.items.forEach(item => {
        item.state = item.state === 0 ? '禁用' : '启用'
      })
      res.items = this.$route.query.name ? res.items.filter(item => item.subjectName === this.$route.query.name) : res.items
      this.tableData = res.items
      this.tagCounts = res.counts
      this.isLoading = false
    },
    // 改变状态
    async clickChangeState (id, state) {
      console.log(id, state)
      const params = {
        id,
        state: state === '禁用' ? 1 : 0
      }
      const { data: res } = await changeState(params)
      console.log(res)
      // 重新渲染表格数据
      this.loadTags(this.currentPage)
      // 控制启用按钮弹出消息
      this.$message({
        message: '操作成功',
        type: 'success'
      })
    },
    // 删除功能
    async removeTags (id) {
      const params = {
        id
      }
      const { data: res } = await remove(params)
      console.log(res)
      this.loadTags(this.currentPage)
      this.$message({
        message: '删除成功',
        type: 'success'
      })
    },
    // 获取学科列表
    async getSubjectsList () {
      const { data: res } = await subJectsList()
      // console.log(res)
      this.subjectsLists = res
    },
    // 新增
    async addTags () {
      const params = {
        subjectID: this.subjectID ? this.subjectID : this.form.subject,
        tagName: this.form.dirname
      }
      const { data: res } = await add(params)
      console.log(res)
      this.$message({
        message: '添加成功',
        type: 'success'
      })
      this.loadTags(1)
      this.dialogFormVisible = false
    },
    // 修改
    async updateTags (id) {
      const params = {
        id,
        subjectID: this.subjectID ? this.subjectID : this.form.subject,
        tagName: this.form.dirname
      }
      const { data: res } = await update(params)
      console.log(res)
      this.$message({
        message: '修改成功',
        type: 'success'
      })
      this.loadTags(1)
      this.dialogFormVisible = false
    },
    // 返回学科
    goBack () {
      // 正常逻辑
      // this.$router.back()

      // 测试逻辑
      this.$router.push({
        path: '/subjects/list'
      })
    }
  },
  created () {
    const queryData = this.$route.query
    this.subjectID = queryData.id ? Number(queryData.id) : ''
    this.subjectName = queryData.name ? queryData.name : ''
    this.loadTags(1)
    this.getSubjectsList()
  }

}
</script>

<style scoped lang='scss'>
.mt10 {
  margin-top: 10px;
}
</style>
